<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="领料单号" prop="getMaterialsFormNumber">
        <el-input
          v-model="queryParams.getMaterialsFormNumber"
          placeholder="请输入领料单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品图号" prop="productDrawingNumber">
        <el-input
          v-model="queryParams.productDrawingNumber"
          placeholder="请输入产品图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="dictGetMaterialsFormStatus">
        <el-select
          v-model="queryParams.dictGetMaterialsFormStatus"
          placeholder="请选择状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_get_materials_form_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <div class="btn">
      <div>
        <el-button
          type="primary"
          @click="batchApprove"
          :loading="approveLoading"
          v-hasPermi="['produce:get-materials-form:approve']"
        >
          批量审批
        </el-button>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['produce:get-materials-form:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['produce:get-materials-form:create']"
        >
          新增
        </el-button>
      </div>
      <div>
        <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
      </div>
    </div>
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length ? true : false"
      @register="register"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :tableHeight="tableHeight"
    >
      <template #action="{ row }">
        <!-- 10 待审批 20 不通过 30 撤回 40 审批中 50 已审批 -->
        <el-button
          link
          type="primary"
          @click="openForm('update', row.id)"
          v-if="[10, 20, 30].includes(row.dictGetMaterialsFormStatus)"
          v-hasPermi="['produce:get-materials-form:update']"
        >
          编辑
        </el-button>
        <el-button
          link
          type="primary"
          @click="approve([row.id])"
          v-if="[10, 30].includes(row.dictGetMaterialsFormStatus)"
          :loading="approveLoading"
          v-hasPermi="['produce:get-materials-form:approve']"
        >
          审批
        </el-button>
        <el-button
          link
          type="primary"
          @click="openForm('view', row.id)"
          v-hasPermi="['produce:get-materials-form:view']"
        >
          查看
        </el-button>
      </template>
    </Table>
  </ContentWrap>

  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getTableTitle" />
</template>

<script setup lang="ts" name="GetMaterialsForm">
import { getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import * as GetMaterialsFormApi from '@/api/produce/workOrderManagement/getMaterialsForm'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
const message = useMessage() // 消息弹窗
// const { t } = useI18n() // 国际化

const queryParams = reactive({
  pageNo: 1,
  productNumber: null,
  productName: null,
  getMaterialsFormNumber: null,
  productDrawingNumber: null,
  dictGetMaterialsFormStatus: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const approveLoading = ref(false)

const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
const code = 'GetMaterialsForm'  //表头名
const tableHeight = ref(0)

// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作getUserLabelPage
const { tableObject, tableMethods } = useTable({
  getListApi: GetMaterialsFormApi.getGetMaterialsFormPage, // 分页接口
  defaultParams: queryParams
})

const parentRef = ref()
// 获取table组件
const register = (parent: any) => {
  parentRef.value = parent
}

// 获得表格的各种操作
const { getList } = tableMethods

// 获取表头
const getTableTitle = async () => {
  const res = await GetMaterialsFormApi.getGetMaterialsFormPage(queryParams)
  res.labels.push({
    field: 'action',
    label: '操作',
    align: 'left',
    headerAlign: 'left',
    width: 170
  })
  const { allSchemas } = useCrudSchemas(res.labels)
  tableTitleList.value = allSchemas.tableColumns
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitleList.value, code)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 修改/查看操作 */
const { push } = useRouter() // 路由
const openForm = (type: string, id?: number) => {
  push({
    path:'/produce/produce/workOrderManagement/getMaterialsFormDetail',
    query: {
      id,
      type
    }
  })
}

// 批量审批
const batchApprove = async () => {
  if (!parentRef.value.selections.length) {
    message.notifyError('请至少选择一条数据')
    return
  }
  const arr = parentRef.value.selections
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]['dictGetMaterialsFormStatus'] !== 10) {
      message.notifyError('只能审批待审批状态的数据')
      return
    }
  }
  const data = parentRef.value.selections.map(item => {
    return item['id']
  })
  approve(data)
}

// 审批
const approve = async (val: number[]) => {
  approveLoading.value = true
  try {
    await GetMaterialsFormApi.approveGetMaterialsForm(val)
    message.success('审批成功')
    getList()
    parentRef.value.clearTableSelect()
    console.log(parentRef.value.selections)
  } finally {
    approveLoading.value = false
  }
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = async () => {
  exportRef.value.open()
}

// 下载
const downloadFun = async () => {
  const val = exportRef.value.params
  let params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = parentRef.value.selections.map((item) => {
      return item['id']
    })
  }
  const data = await GetMaterialsFormApi.exportGetMaterialsForm(params)
  download.excel(data, val.name)
  parentRef.value.clearTableSelect()
}

/** 初始化 **/
onMounted(async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  await getTableTitle()
  getList()
})
</script>
<style lang="scss" scoped>
.btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
